using System.Web.UI;
using Microsoft.SharePoint.WebPartPages;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;

namespace Macaw.Wss3.PageViewerWebPartNoFrames
{
    /// <summary>
    /// ControlAdapter for "Microsoft.SharePoint.WebPartPages.PageViewerWebPart"
    public class PageViewerWebPart_Adapter : System.Web.UI.Adapters.ControlAdapter
    {
        protected override void Render(HtmlTextWriter writer)
        {
            bool inEditMode = false;

            // Get the reference to the PageViewerWebPart-control to which this adapter is connected
            Microsoft.SharePoint.WebPartPages.PageViewerWebPart pvw = this.Control as Microsoft.SharePoint.WebPartPages.PageViewerWebPart;

            // Is the PageViewerWebPart a valid reference?
            if (pvw != null)
            { // Yes!

                // Get the WebPartManager for this page
                SPWebPartManager swpm = (SPWebPartManager)SPWebPartManager.GetCurrentWebPartManager(pvw.Page);

                // Set the flag if WebPart Page-design is allowed
                inEditMode = swpm.GetDisplayMode().AllowPageDesign;
            }
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            base.Render(htw);
            string result = Regex.Replace(sw.GetStringBuilder().ToString(), "<div class=\"UserGeneric\"[^>]*>(.*)?</div>", "<div class=\"PVWFallback\"><a href=\""+ pvw.ContentLink + "\">"+ HttpContext.Current.Server.HtmlEncode( pvw.Title ) +"</a></div>");
            writer.Write(result);
        }
    }
}